from gui.wechat_gui import WechatGui

from myutils.window_helper import *
from model.exception import (
    ParkTokenFatalError,
    ParkTokenTokenParseError,
    ParkTokenWechatHwndError,
)
from model.token import Token, TokenType
import re
import json
from datetime import datetime
import myutils.services_helper as services_helper


class YunGui(WechatGui):
    def set_fiddler_hwnd(self, hwnd):
        self.fiddler_hwnd = hwnd

    def check_env(self):
        super().check_env()
        if not self.fiddler_hwnd:
            raise ParkTokenFatalError("未找到fiddler窗口")

    def extract_token(self, fiddle_text) -> Token:
        """使用正则提取token与openid"""

        # userappid=wx025665218c8f18fc;
        r_appid = re.search(r"userappid=([0-9a-zA-Z]*)", fiddle_text)
        # token=b5022235-de91-4f52-8731-abd13e2f76fa
        r_token = re.search(r"token=([0-9a-zA-Z-]*)", fiddle_text)
        # uin=206572702
        r_uin = re.search(r"uin=([0-9]*)", fiddle_text)

        if r_appid and r_token and r_uin:
            token = Token()
            token.userid = r_uin.group(1)
            token.data = json.dumps(
                {
                    "appid": r_appid.group(1),
                    "token": r_token.group(1),
                    "uin": r_uin.group(1),
                    "updateTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                },
                ensure_ascii=False,
            )
            token.type = TokenType.Yun
            return token
        else:
            raise ParkTokenTokenParseError(fiddle_text)

    def start(self):
        self.check_env()

        self.close_wechat_browser()
        try:
            max_window(self.hwnd)
        except Exception as e:
            raise ParkTokenWechatHwndError("微信窗口已关闭")
        self.click_image("./images/yun/logo.png")
        self.click_image("./images/yun/menu1.png")
        self.click_image("./images/yun/menu2.png")
        max_window(self.fiddler_hwnd)
        self.click_image("./images/yun/fiddler_row.png")
        time.sleep(1.5)  # 等待请求完成
        self.hotkey("ctrl", "shift", "s")
        self.hotkey("ctrl", "x")
        services_helper.save_token(self.extract_token(get_clipboard_text()))
        self.close_wechat_browser()
